from fastapi import FastAPI
from fastapi.responses import JSONResponse
from starlette.requests import Request


def exception_handler(app: FastAPI):
    @app.middleware("http")
    async def catch_exceptions_middleware(request: Request, call_next):
        try:
            return await call_next(request)
        except Exception as e:

            print(f"Unhandled error: {e}")
            return JSONResponse(
                status_code=500,
                content={"code": 500, "msg": "服务器内部错误", "error": str(e)},
            )
